import {Result} from '@/base/Result';
import {request} from '@/base/Request';
import {Page} from '@/base/Page';
import {Agent} from '@/base/model/Agent';
import {TableSort} from '@/base/TableSort';

export interface AgentVM {
  address: string,
  agentName: string,
  linkName: string,
  phone: string,
  roles: Array<any>,
}

export interface AgentAdd {
  address: string,
  agentName: string,
  linkName: string,
  phone: string,
  roles: Array<any>,
  password: string
}

export function getAgentList(params: {
  pageIndex: number,
  pageSize: number,
  sortDirection?: string,
  sortProperties?: string[],
  agentName?: string,
  linkName?: string,
  phone?: string,
  createBegin?: string,
  createEnd?: string,
  companyId?: number[]
}): Promise<Result<Page<Agent>>> {
  let companyIdString = '';
  let sortPropertiesString = '';
  let agentString = '';
  if (params.sortProperties && params.sortProperties.length > 0) {
    sortPropertiesString = params.sortProperties.map(x => 'sortProperties=' + x).join('&');
    delete params.sortProperties;
  }
  if (!params.sortProperties) Object.assign(params, TableSort());
  if (params.companyId && params.companyId.length > 0) {
    companyIdString = params.companyId.map(x => 'companyId=' + x).join('&');
    agentString = sortPropertiesString ? `${sortPropertiesString}&${companyIdString}` : companyIdString;
    delete params.companyId;
  }
  return request.getPage(Agent, '/api/agent?' + agentString, {params});
}

export function getAgent(id: number): Promise<Result<Agent>> {
  return request.get(Agent, `/api/agent/${id}`);
}

export function putAgent(id: number, params: AgentVM): Promise<Result<Agent>> {
  let formData = new FormData();
  Object.keys(params).forEach(x => {
    formData.append(x, params[x]);
  });
  return request.put(Agent, `/api/agent/${id}`, formData);
}

export function postAgent(params: AgentAdd): Promise<Result<Agent>> {
  let formData = new FormData();
  Object.keys(params).forEach(x => {
    formData.append(x, params[x]);
  });
  return request.post(Agent, '/api/agent', formData);
}

export function deleteAgent(id: number): Promise<Result<void>> {
  return request.delete(`/api/agent/${id}`);
}

export function getAgentNum(): Promise<Result<Number>> {
  return request.get(Number, `/api/agent/num/company`);
}
export function putAgentPwd(params: {
  agentId: number,
  password: string
}): Promise<Result<Agent>> {
  let formData = new FormData();
  Object.keys(params).forEach(x => {
    formData.append(x, params[x]);
  });
  return request.put(Agent, `/api/agent/agent-password`, formData);
}
